package com.xin.ssm.controller;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xin.ssm.entity.Employee;
import com.xin.ssm.entity.Msg;
import com.xin.ssm.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class EmployeeController {
    @Autowired
    EmployeeService employeeService;

    /*
      *  查询所有员工数据
      * 转成json字符串的方法
     */
    @ResponseBody
    @RequestMapping(value = "/emps")
    public Msg getEmployees(@RequestParam(value = "pn",defaultValue = "1")Integer pn,Employee employee){
        //要分页要用pageHelper
        //传入页码和分页的大小
        PageHelper.startPage(pn,10);
        //startPage后面紧跟的这个查询就是分页查询
        List<Employee> emps = employeeService.getAll(employee);
        PageInfo<Employee> pageInfo = new PageInfo<>(emps,10);

        System.out.println("emps的值为："+emps);
        System.out.println("page的值为："+pageInfo);
        return Msg.success().add("pageInfo",pageInfo);
    }

//    //查询所有员工数据
//    @GetMapping(value = "/emps")
//    public String getEmployees(@RequestParam(value = "page",defaultValue = "1")Integer page, Model model){
//        PageHelper.startPage(page,5);
//        //startPage后面紧跟的这个查询就是分页查询
//        List<Employee> emps = employeeService.getAll();
//        PageInfo<Employee> pageInfo = new PageInfo<>(emps,10);
//        model.addAttribute("pageInfo",pageInfo);
//
//        System.out.println(pageInfo.toString());
//        return "employee_list";
//    }
        /*--------------------------------------------------------*/
    /**
     * 员工保存
     * JSR303校验
     *
     * @return
     */
    @RequestMapping(value = "/emp",method = RequestMethod.POST)
    @ResponseBody
    public Msg saveEmp(@Valid Employee employee, BindingResult result){
        if(result.hasErrors()){
            Map<String,Object> map = new HashMap<>();
            List<FieldError> errors = result.getFieldErrors();
            for (FieldError fieldError : errors){
                System.out.println("错误的字段名" + fieldError.getField());
                System.out.println("错误信息" + fieldError.getDefaultMessage());
                map.put(fieldError.getField(),fieldError.getDefaultMessage());
            }
            return Msg.fail().add("errorFields",map);
        }else{
            employeeService.saveEmp(employee);
            return Msg.success();
        }
    }

    /**
     * 检查用户名是否可用
     *
     * @param empName
     * @return
     */
    @RequestMapping("/checkuser")
    @ResponseBody
    public Msg checkuser(String empName) {
        //先判断用户名是否是合法的表达式
        String regx = "(^[a-zA-Z0-9_-]{3,16}$)|(^[\\u2E80-\\u9FFF]{2,5})";
        if (!empName.matches(regx)) {
            return Msg.fail().add("va_msg", "用户名需是2-5位中文或者3-16位英文和数字的组合噢");
        }
        //数据库用户名重复校验
        boolean b = employeeService.checkUser(empName);
        if (b) {
            return Msg.success();
        } else {
            return Msg.fail().add("va_msg", "用户名不可用");
        }
    }


    /**
     * 按照员工id查询员工信息，用于修改用户信息的模态框
     *
     * @param id
     * @return
     */

    @RequestMapping(value = "/emp/{id}",method = RequestMethod.GET)
    @ResponseBody
    public Msg getEmp(@PathVariable("id") Integer id){
        Employee employee = employeeService.getEmp(id);
        return Msg.success().add("emp",employee);
    }

    /**
     * 保存修改之后的员工信息
     *
     * @param employee
     * @return
     */
    @RequestMapping(value = "/emp/{empId}", method = RequestMethod.PUT)
    @ResponseBody
    public Msg saveEmp(Employee employee) {
        System.out.println(employee);
        employeeService.updateEmp(employee);
        return Msg.success().add("emp", employee);
    }

    /**
     * 删除用户，不管你多少个我都能删
     * 单个：1
     * 批量：1-2-3
     *
     * @param ids
     * @return
     */
    @RequestMapping(value = "/emp/{ids}", method = RequestMethod.DELETE)
    @ResponseBody
    public Msg deleteEmp(@PathVariable("ids") String ids){
        //批量删除
        if (ids.contains("-")){
            List<Integer> del_ids = new ArrayList<>();
            String[] str_ids = ids.split("-");
            //组装id集合
            for (String s : str_ids){
                del_ids.add(Integer.parseInt(s));
            }
            employeeService.deleteBatch(del_ids);
        }else { //单个删除
            Integer id = Integer.parseInt(ids);
            employeeService.deleteEmp(id);
        }
        return Msg.success();
    }

}
